package org.csu.jpetstore.web.servlet;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Product;
import org.csu.jpetstore.service.CatalogService;
import org.csu.jpetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ViewHistoryServlet extends HttpServlet {

    private static final String VIEW_HISTORY = "/WEB-INF/jsp/catalog/history.jsp";

    private LogService logService;
    private CatalogService catalogService;
    private List<String> historyList;
    private List<Product> productList;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("loginAccount");

        logService = new LogService();
        catalogService = new CatalogService();

        historyList = logService.getHistory(account.getUsername());
        productList = new ArrayList<Product>();
        for(int i=0;i<historyList.size();i++) {
            Product product = catalogService.getProduct(historyList.get(i));
            if(!contain(product)) {
                product.setViewTime(logService.getViewTime(account.getUsername(), product));
                productList.add(product);
            }
        }


        session.setAttribute("historyList",productList);

        request.getRequestDispatcher(VIEW_HISTORY).forward(request,response);
    }

    private boolean contain(Product product) {
        for(int i=0;i<productList.size();i++) {
            if(productList.get(i).getProductId().equals(product.getProductId()))
                return true;
        }
        return false;
    }

}
